package util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;

public class Screenshot {

    public static byte[] convertToByte(BufferedImage img, double quality, double scale) throws IOException {
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality((float) quality);
        
        if (scale != 1.0) {
            img = getScaledInstance(img, scale);
        }

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        writer.setOutput(new MemoryCacheImageOutputStream(bout));
        writer.write(null, new IIOImage(img, null, null), iwp);
        writer.dispose();
        bout.flush();
        
        return bout.toByteArray();
    }
    
    public static BufferedImage convertToBufferedImage(byte[] img) throws IOException {
        return ImageIO.read(new ByteArrayInputStream(img));
    }

    private static BufferedImage getScaledInstance(BufferedImage src, double scale) {
        int width = (int) (src.getWidth() * scale);
        int height = (int) (src.getHeight() * scale);

        Image scaled = src.getScaledInstance(width, height, BufferedImage.SCALE_AREA_AVERAGING);
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        result.createGraphics().drawImage(scaled, 0, 0, width, height, null);
        
        return result;
    }
}
